import { toRaw } from "vue"
import { defineStore } from "pinia"
import { userApi } from "@/mock"
import sysLayout_routes, { sysLayout_init_routes, sysLayout_constant_routes } from "@/router/route.config"
import { listToTree, deepClone ,sortTreeArr} from "@/common/utils"
import { authRouteMode } from "@/common/config"

const views: Record<string, any> = import.meta.glob(["/src/views/**/*.vue",])
// console.log(views)


// 根据用户具备权限的路由表生成菜单数据
function getMenu(routes: routeItemConfig[]) {
  const menu = routes.filter(v => {
    if (!v.meta.noInMenu) {
      v.key = v.name
      if (v.children) v.children = getMenu(v.children)
      return true
    }
  })
  //  return menu.sort((a,b)=>a.meta.rank-b.meta.rank)
  return menu
}

// 采用远程路由表方案时，需要格式化一下路由配置项
function formatRoutes(routes: routeTreeNode[]): routeItemConfig[] {
  const metaKeys = ['noNeedAuth', 'title', 'icon', 'noKeepAlive', 'affix', 'noInMenu', 'hiddenMenu', 'hiddenLayout', 'rank','actionList','link']
  const accessedRoutes: routeItemConfig[] = []

  routes.forEach(v => {
    // meta处理
    v.meta = { title: '' }
    metaKeys.forEach(i => {
      if (Object.keys(v).includes(i)) {
        v.meta[i] = v[i]
        delete v[i]
      }
    })

    // componet处理
    if (v.component) {
      if (views["/src/views" + v.component]) v.component = views["/src/views" + v.component]
      else console.log(new Error(`无法找到/src/views${v.component}对应路径的组件`))
    }
    accessedRoutes.push(v)
  })
  return listToTree<routeTreeNode>(accessedRoutes as any, 'id', 'pId', true, (node) => {
    // 去除多余的属性
    delete node.accessRequestList
    delete node.requestList
    delete node.pName
    delete node.pTitle
  }).children
}



export default defineStore('routes', {
  state: () => ({
    routeConfig: [] as routeItemConfig[],      // 当前用户具备的路由配置，可以 router.addRoute(routeConfig)
    accessedRoutes: [] as routeItemConfig[],   // 当前用户可以访问的路由项
    menu: authRouteMode == 'local' ?           // 当前用户具备的菜单
      sortTreeArr(getMenu(sysLayout_routes[0].children as routeItemConfig[]),'meta.rank') :
      [] as routeItemConfig[],
    accessRequestNameList: [] as string[],     // 当前用户可访问的接口
  }),
  actions: {
    setRouteConfig(config: routeItemConfig[]) {
      this.routeConfig = config
    },
    addAccessedRoutes(accessedRoutes: routeItemConfig[]) {
      this.accessedRoutes.push(...accessedRoutes)
    },
    setMenu(menu: any[]) {
      this.menu =menu
      console.log('menu', menu)
    },
    clearRoutes() {
      this.accessedRoutes = []
      this.routeConfig = []
      this.menu = []
    },
    // 远程路由表方案的权限设置，单独的接口返回路由表
    async setAuth(token: string) {
      const res = await userApi.getRolesInfo(token)
      if (res.code == 201) return { code: 201, accessedRoutes: [] }
      if (res.code == 200) {
        this.addAccessedRoutes(formatRoutes(res.routes))
        this.accessRequestNameList = res.accessRequestNameList
        console.log("可访问的接口",toRaw(this.accessRequestNameList))
        console.log("可访问的路由",toRaw(this.accessedRoutes))
      }
      this.addAccessedRoutes(sysLayout_constant_routes)
      this.setMenu(sortTreeArr(getMenu(deepClone(this.accessedRoutes)),'meta.rank')) 
      const routes = deepClone(sysLayout_init_routes)
      routes[0].children.push(...toRaw(this.accessedRoutes))
      this.setRouteConfig(routes)
      return { code: res.code == 200 ? 200 : 0, accessedRoutes: routes }
    },
    // 远程路由表方案的权限设置，登录接口返回路由表。同样也是在permmsion.ts里调用，routes通过pinia的user模块读取
    async setAuth1(routes: routeTreeNode[]) {
      let isSuccess = true
      if (routes.length) isSuccess = false
      this.addAccessedRoutes(formatRoutes(routes))
      this.addAccessedRoutes(sysLayout_constant_routes)
      this.setMenu(sortTreeArr(getMenu(deepClone(this.accessedRoutes)),'meta.rank')) 
      const routeConfig = deepClone(sysLayout_init_routes)
      routeConfig[0].children.push(...toRaw(this.accessedRoutes))
      this.setRouteConfig(routeConfig)
      return { code: isSuccess ? 200 : 0, accessedRoutes: routeConfig }
    }
  },

})